package com.tianyu.inspection.common.model;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**********************************
 * @Author YSW
 * @Description 汉语转拼音字母工具类
 * @Date 2021/1/12 - 11:51
 **********************************/

public class ChineseToLetterModel {

    /**
     * 将汉字转换为全拼
     * @param src 字符串（汉字）
     * @return
     */
    public static String getPingYin(String src) {
        char[] t1;
        t1 = src.toCharArray();
        String[] t2 = new String[t1.length];
        HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
        t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        t3.setVCharType(HanyuPinyinVCharType.WITH_V);
        StringBuilder t4 = new StringBuilder();
        int t0 = t1.length;
        for (char c : t1) {
            // 判断是否为汉字字符
            if (Character.toString(c).matches(
                    "[\\u4E00-\\u9FA5]+")) {
                try {
                    t2 = PinyinHelper.toHanyuPinyinStringArray(c, t3);
                } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
                    badHanyuPinyinOutputFormatCombination.printStackTrace();
                }
                t4.append(t2[0]);
            } else {
                t4.append(c);
            }
        }
        return t4.toString();
    }

    /**
     * 返回中文的首字母
     * @param str 字符串（汉字）
     * @return
     */
    public static String getPinYinHeadChar(String str) {
        String convert = "";
        for (int j = 0; j < str.length(); j++) {
            char word = str.charAt(j);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert += pinyinArray[0].charAt(0);
            } else {
                convert += word;
            }
        }
        return convert;
    }

    /**
     * 将字符串转移为ASCII码
     * @param cnStr 字符串
     * @return ASCII码
     */
    public static String getCnAscii(String cnStr) {
        StringBuilder strBuf = new StringBuilder();
        byte[] gbk = cnStr.getBytes();
        for (int i = 0; i < gbk.length; i++) {
            strBuf.append(Integer.toHexString(gbk[i] & 0xff));
        }
        return strBuf.toString();
    }
}